


function ajax(method, url, data, token) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();

    xhr.onreadystatechange = function () {
      if (xhr.readyState == 4) {
        if (xhr.status == 200) {
          resolve(xhr.response);
        } else {
          reject(xhr.status);
        }
      }
    }

    if (method.toLowerCase() != 'post') {
      //对象转为get参数
      let s = '';
      for (item in data) {
        s += '&' + item + '=' + encodeURIComponent(data[item])
      }
      url += '?' + s.slice(1);
    }

    xhr.open(method, url, true);


    if (method.toLowerCase() == 'post' && data.constructor != FormData) {
      xhr.setRequestHeader('Content-Type', 'Application/json');
    }

    xhr.responseType = 'json';

    if (token) {
      xhr.setRequestHeader('Authorization', 'Bearer ' + token);
    }

    if (method.toLowerCase() == 'post') {
      if (data.constructor != FormData) {
        xhr.send(JSON.stringify(data))
      } else {
        xhr.send(data);
      }

    } else {
      xhr.send();
    }
  })
}

export default ajax;